import {getDocDeptPageList} from "@/api/document/myDocument.js";
import {isNull} from "@/utils/validate.js";

export function deptFunctions(deptListDialogOpen, deptOpProp, docForm) {
    function openDeptDialog(displayPropName, submitPropName='') {
        deptListDialogOpen.value = true
        deptOpProp.displayPropName = displayPropName
        deptOpProp.submitPropName = submitPropName
    }

    const closeDeptDialog = () => {
        deptListDialogOpen.value = false
    }

    function getDeptList(queryParams, callback) {
        getDocDeptPageList(queryParams).then(res => {
            res.dialogTitle = '选择部门'
            callback(res)
        })
    }

    const handleSelectedDept = (depts) => {
        let deptIds ='', deptNames = ''
        for (const dept of depts) {
            deptIds = deptIds.concat(',' + dept.id)
            deptNames = deptNames.concat(',' + dept.name)
        }
        deptIds = deptIds.substring(1, deptIds.length)
        deptNames = deptNames.substring(1, deptNames.length)
        if (!isNull(deptOpProp.submitPropName)) {
            docForm.value[deptOpProp.submitPropName] = deptIds
        }
        docForm.value[deptOpProp.displayPropName] = deptNames
        deptListDialogOpen.value = false
    }

    const clearSendUnit = () => {
        docForm.value.sendUnit = ''
    }

    const clearMainSendUnits = () => {
        docForm.value.mainSendUnits = ''
        docForm.value.mainSendUnitIds = null
    }

    const clearCopySendUnits = () => {
        docForm.value.copySendUnits = ''
        docForm.value.copySendUnitIds = null
    }

    return {
        openDeptDialog,
        closeDeptDialog,
        getDeptList,
        handleSelectedDept,
        clearSendUnit,
        clearMainSendUnits,
        clearCopySendUnits
    }
}
